package one.bugu.android.demon.util;

import java.util.LinkedList;
import java.util.Random;

import android.widget.TextView;

/**
 * 滚动文字动效工具类
 */
public class NumScrollAnimUtils {

    /**
     * 每秒刷新多少次
     */
    private static final int COUNTPERS = 50;

    /**
     * 每次增加的数量
     */
    private static double afterNum;

    /**
     * 开始动画
     *
     * @param textV    z展示文本的控件
     * @param afterNum 改变前数据
     * @param addNum   增加的数量
     * @param time     动画时间
     */
    public static void startAnim(TextView textV, double addNum, double afterNum, long time) {
        if (afterNum == 0 && addNum == 0) {
            textV.setText(NumUtils.NumberFormat(afterNum, 12));
            return;
        }
        NumScrollAnimUtils.afterNum = afterNum;
        Double[] nums = splitnum(addNum, (int) ((time / 1000f) * COUNTPERS));
        Counter counter = new Counter(textV, nums, time);
        textV.removeCallbacks(counter);
        textV.post(counter);
    }

    /**
     * 显示数据处理
     *
     * @param num   数据
     * @param count 拆分的个数
     * @return
     */
    private static Double[] splitnum(double num, int count) {
        Random random = new Random();
        double numtemp = num;
        double sum = 0;
        LinkedList<Double> nums = new LinkedList<>();
        nums.add(0.0);
        while (true) {
            float nextFloat = NumUtils.NumberFormatFloat(
                    (random.nextFloat() * num * 2f) / (float) count, 12);
            if (numtemp - nextFloat >= 0) {
                sum = NumUtils.NumberFormatFloat(sum + nextFloat, 12);
                nums.add(sum);
                numtemp -= nextFloat;
            } else {
                nums.add(num);
                return nums.toArray(new Double[0]);
            }
        }
    }

    /**
     * 设置一个Runable线程对象在delayMillis毫秒后执行文字显示
     */
    static class Counter implements Runnable {
        private final TextView view;
        private Double[] nums;
        private long pertime;
        private int i = 0;

        Counter(TextView view, Double[] nums, long time) {
            this.view = view;
            this.nums = nums;
            this.pertime = time / nums.length;
        }

        @Override
        public void run() {
            if (i > nums.length - 1) {
                view.removeCallbacks(Counter.this);
                return;
            }
            view.setText(NumUtils.NumberFormat((nums[i++] + afterNum), 12));
            view.removeCallbacks(Counter.this);
            view.postDelayed(Counter.this, pertime);
        }
    }
}
